#pragma once
#include <iostream>
#include <string>
#include <memory>
#include<sstream>
#include <unordered_map>
#include "Socket.hpp"
#include "Tcpserver.hpp"
#include "Util.hpp"
#include "Log.hpp"

const std::string gspace = " "; // 空格
const std::string glinespace = "\r\n"; // 回车换行
const std::string gsep_kv = ": "; // 键值对分隔符
const std::string webroot = "./wwwroot"; // 网络根目录
const std::string homepage = "/index.html"; // 默认首页


class HttpRequest{
public:

	HttpRequest()
	:_method(""),
	_uri("/"),
	_version("HTTP/1.1")
	{}

	std::string Serialize(std::string reqline){
		return std::string("");
	}

	// 解析请求行
	void Parse(std::string &reqline){
		std::stringstream ss(reqline);
		ss >> _method >> _uri >> _version;
	}
	bool Deserialize(std::string &reqstr){
		std::string reqline;
		bool res = Util::GetOneLine(reqstr, reqline, glinespace);
		if(!res)
			return false;

		Parse(reqline);

		if(_uri == "/"){
			_uri = webroot + "index.html";
		}
		else{
			_uri = webroot + _uri;
		}

		return true;
	}

	std::string GetURI() const {
		return _uri;
	}

	~HttpRequest(){}

private:
	std::string _method; // 请求方法
	std::string _uri; // 请求资源路径
	std::string _version; // HTTP版本
	std::unordered_map<std::string, std::string> _header; // 请求报头
	std::string _data; // 请求正文

};


class HttpResponse{
public:

	HttpResponse(){}

	std::string Serialize(){
		// 构建状态行
		std::string stateline = _version + " " + std::to_string(_status) + " " + _des + glinespace;

		// 构建响应头
		std::string res_header;
		for(auto header : _header){
			std::string line = header.first + gsep_kv + header.second + glinespace;
			res_header += line;
		}

		std::string res = stateline + res_header + glinespace + _data;
		return res;
	}
	~HttpResponse(){}

private:
	std::string _version; // HTTP版本
	int _status; // 状态码
	std::string _des; // 状态码描述
	std::unordered_map<std::string, std::string> _header; // 响应报头
	std::string _data; // 响应正文
};

class Http{
public:

	Http(){}

	~Http(){}

private:
	std::unique_ptr<Tcpserver> _server;
};